package com.bunnyhsu.service.impl;

import com.bunnyhsu.mapper.AdminMapper;
import com.bunnyhsu.model.Admin;
import com.bunnyhsu.service.AdminService;
import com.bunnyhsu.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by xl on 2018/4/12.
 */
@Service
public class AdminServiceImpl implements AdminService{

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin login(String id, String pwd) {
        Admin admin = adminMapper.selectAdmin(id);
        if(admin!=null)
        {
            if(admin.getPwd().equals(MD5Util.md5(pwd)))
            {
                String token = makeToken(id, pwd);
                if(updateToken(id, token))
                {
                    admin.setAccess_token(token);
                    admin.setPwd("");
                    return admin;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

    @Override
    public String makeToken(String id, String pwd) {
        String token = MD5Util.md5(id + new java.util.Date().getTime() + pwd);
        return token;
    }

    @Override
    public Boolean updateToken(String id, String token) {
        try
        {
            adminMapper.updateAdminToken(token, id);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    @Override
    public Boolean comfirmToken(String token) {
        Admin admin = adminMapper.selectAdminByToken(token);
        if (admin==null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}
